package cn.fldong.employee.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

    // [3]添加注解，并指定过滤的 URL
@WebFilter("*.jsp")
    // [1]以xxxFilter.java命名，并实现 Filter 接口
public class AuthFilter implements Filter {
    // [2]实现 Filter 接口的 doFilter 方法
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 1. 转换请求响应类型
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 设置编码,防止中文乱码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 2. 判断用户是否登录
        HttpSession session = request.getSession();
        Object user = session.getAttribute("username");
        if (user == null) {
            // 未登录，重定向到登录页面
            response.sendRedirect("login.html");
        }else {
            // 已登录，放行
            filterChain.doFilter(request, response);
        }
    }
}
